package cn.iocoder.yudao.module.ordering.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.ordering.dal.dataobject.ThirdPartyMemberDO;
import cn.iocoder.yudao.module.ordering.dal.mysql.ThirdPartyMemberMapper;
import cn.iocoder.yudao.module.ordering.service.ThirdPartyMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 第三方会员信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class ThirdPartyMemberServiceImpl implements ThirdPartyMemberService {

    @Resource
    private ThirdPartyMemberMapper thirdPartyMemberMapper;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public ThirdPartyMemberDO syncSingleMemberByToken(String token) {
        if (StrUtil.isBlank(token)) {
            log.warn("通过token同步会员信息失败：token为空");
            return null;
        }

        try {
            // 调用第三方API获取会员信息
            String url = "https://api.yirun.yjdz.shop/v1/member/member/index";
            HttpResponse response = HttpRequest.get(url)
                    .header("Authorization", "Bearer " + token)
                    .timeout(10000) // 10秒超时
                    .execute();

            if (response.isOk()) {
                String responseBody = response.body();
                log.info("第三方API响应：{}", responseBody);
                
                // 解析响应数据
                JSONObject jsonObject = JSONUtil.parseObj(responseBody);
                if (jsonObject.getInt("errno", -1) == 0) {
                    // 成功响应，处理会员数据
                    JSONArray dataArray = jsonObject.getJSONArray("data");
                    if (dataArray != null && !dataArray.isEmpty()) {
                        // 获取第一个会员数据（通常第三方登录只返回当前用户信息）
                        JSONObject memberData = dataArray.getJSONObject(0);
                        return syncMemberDataToLocal(memberData);
                    } else {
                        log.warn("第三方API返回的会员数据为空");
                    }
                } else {
                    log.error("第三方API返回错误：{}", responseBody);
                }
            } else {
                log.error("第三方API请求失败，状态码：{}", response.getStatus());
            }
        } catch (Exception e) {
            log.error("通过token同步会员信息异常", e);
        }
        
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean syncMemberToSystemUsers(ThirdPartyMemberDO memberData) {
        try {
            if (memberData == null || StrUtil.isBlank(memberData.getUsername())) {
                log.warn("会员数据为空或用户名为空，无法同步到 system_users 表");
                return false;
            }

            // 检查 system_users 表中是否已存在该用户
            String checkSql = "SELECT COUNT(*) FROM system_users WHERE username = ?";
            Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, memberData.getUsername());
            
            if (count != null && count > 0) {
                // 用户已存在，更新信息
                String updateSql = "UPDATE system_users SET " +
                        "nickname = ?, " +
                        "mobile = ?, " +
                        "realname = ?, " +
                        "tenant_id = ?, " +
                        "update_time = NOW() " +
                        "WHERE username = ?";
                
                jdbcTemplate.update(updateSql,
                        memberData.getNickname(),
                        memberData.getMobile(),
                        memberData.getRealname(),
                        memberData.getTenantId(),
                        memberData.getUsername());
                
                log.info("更新 system_users 表成功，用户名: {}", memberData.getUsername());
            } else {
                // 用户不存在，插入新用户
                String insertSql = "INSERT INTO system_users (username, nickname, mobile, realname, tenant_id, status, create_time, update_time) " +
                        "VALUES (?, ?, ?, ?, ?, 1, NOW(), NOW())";
                
                jdbcTemplate.update(insertSql,
                        memberData.getUsername(),
                        memberData.getNickname(),
                        memberData.getMobile(),
                        memberData.getRealname(),
                        memberData.getTenantId());
                
                log.info("插入 system_users 表成功，用户名: {}", memberData.getUsername());
            }
            
            return true;
        } catch (Exception e) {
            log.error("同步到 system_users 表失败", e);
            return false;
        }
    }

    /**
     * 将第三方会员数据同步到本地数据库
     *
     * @param memberData 第三方会员数据
     * @return 同步后的会员信息对象
     */
    private ThirdPartyMemberDO syncMemberDataToLocal(JSONObject memberData) {
        try {
            // 解析第三方会员数据
            String thirdPartyMemberId = memberData.getStr("id");
            String realname = memberData.getStr("realname");
            String nickname = memberData.getStr("nickname");
            String mobile = memberData.getStr("mobile");
            String username = memberData.getStr("username");
            String mercantId = memberData.getStr("mercant_id");
            
            // 将 mercant_id 转换为 tenantId
            Long tenantId = null;
            if (StrUtil.isNotBlank(mercantId)) {
                try {
                    tenantId = Long.parseLong(mercantId);
                } catch (NumberFormatException e) {
                    log.warn("mercant_id 转换失败: {}", mercantId);
                }
            }
            
            // 检查是否已存在该会员
            ThirdPartyMemberDO existingMember = thirdPartyMemberMapper.selectByThirdPartyMemberId(thirdPartyMemberId);
            
            ThirdPartyMemberDO memberDO;
            if (existingMember != null) {
                // 更新现有会员信息
                memberDO = existingMember;
                memberDO.setRealname(realname);
                memberDO.setNickname(nickname);
                memberDO.setMobile(mobile);
                memberDO.setUsername(username);
                memberDO.setMercantId(mercantId);
                memberDO.setTenantId(tenantId);
                memberDO.setSyncTime(LocalDateTime.now());
                memberDO.setSyncStatus(1);
                memberDO.setSyncRemark("同步成功");
                memberDO.setUpdateTime(LocalDateTime.now());
                
                thirdPartyMemberMapper.updateById(memberDO);
                log.info("更新第三方会员信息成功，ID: {}", memberDO.getId());
            } else {
                // 创建新会员
                memberDO = ThirdPartyMemberDO.builder()
                        .thirdPartyMemberId(thirdPartyMemberId)
                        .realname(realname)
                        .nickname(nickname)
                        .mobile(mobile)
                        .username(username)
                        .mercantId(mercantId)
                        .tenantId(tenantId)
                        .status(1)
                        .platform("yirun")
                        .syncTime(LocalDateTime.now())
                        .syncStatus(1)
                        .syncRemark("同步成功")
                        .remark("第三方同步")
                        .build();
                
                thirdPartyMemberMapper.insert(memberDO);
                log.info("创建第三方会员信息成功，ID: {}", memberDO.getId());
            }
            
            // 同步到 system_users 表
            syncMemberToSystemUsers(memberDO);
            
            return memberDO;
        } catch (Exception e) {
            log.error("同步第三方会员数据到本地失败", e);
            return null;
        }
    }

}

